package com.fw.ui.servlet;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.fw.ui.bao.MessageBAO;
import com.fw.ui.bao.PropertyBAO;

/**
 * Servlet implementation class StartupServlet
 */
@Component
@Scope(SCOPE_PROTOTYPE)
public class StartupServlet extends GenericServlet {
    static final long serialVersionUID = (long) 1.00;

    @Autowired
    private PropertyBAO propertyBAO;
    @Autowired
    private MessageBAO messageBAO;

    private Logger logger = LoggerFactory.getLogger(StartupServlet.class);

    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    }

    public void init(ServletConfig config) throws ServletException {
	SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
	try {
	    boolean isInitialProperties = propertyBAO.initialSystemProperties();
	    // boolean isInitialProperties = propertyBAO.initialSystemPropertiesUI();
	    if (isInitialProperties) {
		logger.info("CONNECTED TO SERVICE, THE SERVER STARTED...");
	    } else {
		logger.info("CAN NOT CONNECTED TO SERVICE, THE SERVER NOT STARTED !!!");
		System.exit(0);
	    }

	    boolean isInitialMessages = messageBAO.initialSystemMessage(Locale.US);
	    // boolean isInitialMessages = messageBAO.initialSystemMessageUI(Locale.US);
	    if (isInitialMessages) {
		logger.info("CONNECTED TO SERVICE, THE SERVER STARTED...");
	    } else {
		logger.info("CAN NOT CONNECTED TO SERVICE, THE SERVER NOT STARTED !!!");
		System.exit(0);
	    }
	} catch (Exception e) {
	    logger.error("CONNECTED TO SERVICE FAILED, THE SERVER NOT STARTED !!! : " + e.getMessage());
	    e.printStackTrace();
	    System.exit(0);
	}

    }

}
